package etnorservice.etnor_service.controller;



import etnorservice.etnor_service.domain.dto.ApiParameterDTO;
import etnorservice.etnor_service.domain.dto.ApiParameterRequest;
import etnorservice.etnor_service.domain.dto.ApiPublishConfigRequest;
import etnorservice.etnor_service.domain.po.*;
import etnorservice.etnor_service.domain.vo.ApiAduit;
import etnorservice.etnor_service.domain.vo.ApiDetailsVO;
import etnorservice.etnor_service.request.*;
import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.DeviceInfoService;
import etnorservice.etnor_service.service.IApiService;
import etnorservice.etnor_service.service.UserService;
import etnorservice.etnor_service.utils.AesUtil;
import etnorservice.etnor_service.utils.JwtTokenUtil;
import etnorservice.etnor_service.utils.RoleSecurityUtils;
import etnorservice.etnor_service.utils.SnowflakeIdGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/06/30/11:16
 **/
@RestController
public class ApiController {
    @Value("${baseUrl.bocker}")
    String baseUrl;
    @Autowired
    IApiService iApiService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleSecurityUtils roleSecurityUtils;

    @GetMapping("/apiList")
//    @Api(tags = "api获取的接口")
    public Result apiList() throws Exception {
        Result result = new Result();
        result.setCode(200);
        List<ApiDTO> allApis = iApiService.getAllApi();

//        for(ApiDTO apiDTO:allApis){
//            apiDTO.setApiurl()
//        }
        result.setData(allApis);
        List<ApiCategory> apiCategoryList = iApiService.apiKinds();

        result.setApiKinds(apiCategoryList);

        return result;
    }

    //管理端：根据租户id获取属于租户的api
    @GetMapping("/system/apis")
    public Result apis(@RequestHeader(value = "Authorization", required = false)
                               String authorizationHeader) {

        Result result = new Result();
        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Integer id = Integer.parseInt(account);
        Integer talentId = userService.findRoleByAccount(id).getId();
        result.setCode(200);
        result.setData(iApiService.getApisByTalentId(talentId));

        return result;
    }

    @PostMapping("/searchApi")
    public Result searchApi(@RequestBody SearchApiRequest searchApiRequest) {
        searchApiRequest.setCatelog(
                searchApiRequest.getCatelog().equals("all") ? null : searchApiRequest.getCatelog()
        );
        System.out.println("前端参数" + searchApiRequest.getKeywords() + ":" + searchApiRequest.getCatelog());
        Result result = new Result();
        List<ApiDTO> apiList = iApiService.getApisByKewordsAndCatelog(searchApiRequest.getKeywords(), searchApiRequest.getCatelog());
        result.setData(apiList);
        System.out.println("搜索结果：" + apiList);
        result.setCode(200);
        return result;


    }

    @PostMapping("/system/apiAdd")
    public Result addApi(@RequestBody ApiRequest apiReques, @RequestHeader(name = "Authorization", required = false) String token) {
        Result result = new Result();

        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(token));
        Integer id = Integer.parseInt(account);
        apiReques.setTalentid(userService.findRoleByAccount(id).getId());

        SnowflakeIdGenerator generator = new SnowflakeIdGenerator(1, 1);
        apiReques.setApiid(generator.nextId());
        iApiService.addApi(apiReques);
        //        ApiRejectRequest apiRejectRequest= new ApiRejectRequest();
//        apiRejectRequest.setApiId();
//        apiRejectRequest.setNote(null);
//        apiRejectRequest.setCreatetime(new Date());
//        apiRejectRequest.setState(1);
//        apiRejectRequest.setStatus(0);

        return result;
    }

    @GetMapping("/system/catelog")
    public Result getCatelog() {
        Result result = new Result();
        result.setCode(200);
        List<ApiCategory> apiCategoryList = iApiService.apiKinds();
        result.setApiKinds(apiCategoryList);
        return result;
    }

    @GetMapping("/system/apiReview")
    public Result getApiReview(@RequestHeader(value = "Authorization", required = false)
                                       String authorizationHeader) {
        Result result = new Result();
        if (!roleSecurityUtils.isAdmin(authorizationHeader)) {
            result.setMessage("抱歉，您无权使用");
            result.setCode(40001);

        } else {
            result.setData(iApiService.findApiReviewList());
            result.setCode(200);
        }
        return result;
    }

    @GetMapping("/system/reviewMode")
    public Result getReviewModes(@RequestHeader(value = "Authorization", required = false)
                                         String authorizationHeader) {
        Result result = new Result();
        if (!roleSecurityUtils.isAdmin(authorizationHeader)) {
            result.setMessage("抱歉，您无权使用");
            result.setCode(40001);

        } else {
            result.setData(iApiService.findModes());
            result.setCurrentMode(iApiService.findCurrentMode());
            result.setCode(200);
        }
        return result;
    }

    @GetMapping("/system/changeMode")
    public Result changeMode(@Param("modeId") Integer modeId) {
        Result result = new Result();
        int updete = iApiService.changeMode(modeId);
        if (updete > 0) {
            result.setCode(200);
            result.setMessage("更新成功");
        } else {
            result.setCode(400);
            result.setMessage("更新失败");
        }
        return result;
    }

    @GetMapping("/system/passApi")
    public Result passApiReview(@Param("apiId") Integer apiId) {
        Result result = new Result();
        Long apiid = Long.parseLong(iApiService.findApiByid(apiId).getApiid());
        try {
            iApiService.passApiReview(apiid);
            result.setCode(200);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("更新状态失败");
        }

        return result;
    }


    private String extractTokenFromHeader(String header) {
        if (header == null || !header.startsWith("Bearer ")) {
            return null;
        }
        return header.substring(7).trim(); // 去除 "Bearer ".length() 后面的空格
    }


    @GetMapping("/system/reject")
    public Result rejectApi(
            @RequestParam("apiId") String apiId,
            @RequestParam("comment") String comment) {
        Result result = new Result();
        ApiRejectRequest apiRejectRequest = new ApiRejectRequest();
        apiRejectRequest.setApiId(Integer.parseInt(apiId));
        apiRejectRequest.setNote(comment);
        apiRejectRequest.setTime(new Date());
        apiRejectRequest.setState(1);
        apiRejectRequest.setStatus(0);
        try {
            iApiService.rejectAndInsert(apiRejectRequest);
            result.setCode(200);
            result.setMessage("成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("失败");
            result.setCode(400);
        }
        return result;
    }

    @GetMapping("/system/auditList")
    public Result getAduitList(
            @RequestHeader(value = "Authorization", required = false)
                    String authorizationHeader) {
        Result result = new Result();
        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Integer id = Integer.parseInt(account);
        Integer talentId = userService.findRoleByAccount(id).getId();
        List<ApiAduit> apiAduits = iApiService.getAduitList(talentId);
        result.setData(apiAduits);
        result.setCode(200);
        return result;
    }

    /*发布基础数据响应*/
    @GetMapping("/system/basePolicy")
    public Result getPolicy() {
        Result result = new Result();
        result.setData(iApiService.findAllPolicy());


        return result;
    }

    @PostMapping("/system/publishApi")
    public Result publishApi(@RequestBody PublishRequest request,
                             @RequestHeader(value = "Authorization", required = false)
                                     String authorizationHeader) {
        Result result = new Result();
        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Integer id = Integer.parseInt(account);
        String publish = userService.findRoleByAccount(id).getAccount();
        request.setPublishPeople(publish);
        System.out.println("api发布" + request);
        iApiService.publishApi(request);
        // 处理发布逻辑
        // 这里可以添加具体的业务逻辑，例如保存到数据库、通知相关人员等

        // 返回成功响应
        return result;
    }


    @GetMapping("/findDevelopers")
    public Result findDevelopers() {
        Result result = new Result();
        result.setData(userService.findDevelopers());
        return result;
    }

    @GetMapping("/findDevelopers/{id}")
    public Result findDeveloperById(@PathVariable("id") String creatorId) {
        Result result = new Result();
        result.setData(userService.findDeveloperById(Integer.parseInt(creatorId)));
        return result;
    }

    //根据apiid查找某个api信息
    @GetMapping("/api/details/{apiid}")
    public Result findApiById(@PathVariable("apiid") String apiid) throws Exception {
        Result result = new Result();
//        apiid=AesUtil.decrypt(apiid);
        try {
            ApiDetailsVO apiById = iApiService.findApiById(apiid);
            result.setData(apiById);
            result.setCode(200);
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    @PostMapping("/system/api/submit")
    public Result<String> submitApi(@RequestBody ApiSubmission submission,
                                    @RequestHeader(name = "Authorization", required = false) String token) {
        // 处理提交的数据

        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(token));
        Integer id = Integer.parseInt(account);
        //如果apiAuthor为空表示为原创作者，系统自动绑定
        if (submission.getApiAuthor() == "") {
            submission.setApiAuthor(userService.findRoleByAccount(id).getUsername());
        }
        Result result = new Result();
        submission.setTalentId(Integer.parseInt(userService.findRoleByAccount(id).getAccount()));
        try {
            iApiService.submitApi(submission);
            result.setCode(200);

        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("系统错误");
            e.printStackTrace();
        }
        return result;
    }


    @PostMapping("/system/api/uploadImage")
    public ResponseEntity<Object> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("上传的文件为空", HttpStatus.BAD_REQUEST);
        }

        // 定义上传文件的存储路径
        String uploadDir = "path/to/upload/directory"; // 请根据实际情况进行修改
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        File dest = new File(uploadDir, fileName);
        System.out.println("文件"+file);
        try {
            // 将文件保存到指定路径
            file.transferTo(dest);
            String fileUrl = "/uploaded/images/" + fileName; // 假设这是文件在服务器上访问的 URL

            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    /*
    * 接口管理的控制器，可以用于条件查询
    *
    * */
    @PostMapping("/system/api/getList")
    public Result getApiManagementList(@RequestBody ApiSearchRequest apiSearchRequest){
        Result result = new Result();
        System.out.println(apiSearchRequest);
        result.setData(iApiService.findApiList(apiSearchRequest));
        return result;
    }

    @GetMapping("/system/api/getApiCounts")
    public Result getApiCounts(){
        Result result=new Result();
        result.setData(iApiService.getApiCounts());

        return result;
    }

    @GetMapping("/system/api/author/getApiList")
    public Result getApiList(@RequestHeader(value = "Authorization", required = false)
                                     String authorizationHeader) {
        Result result = new Result();
        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));

         result.setData(iApiService.getApisByAccount(account));
         return result;

    }
    @PostMapping("/system/publish/submitParms")
    public Result submitParms(@RequestBody ApiParamsRequest apiParamsRequest,
                              @RequestHeader(value = "Authorization", required = false)
            String authorizationHeader) {
        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));

        Result result = new Result();
        apiParamsRequest.setTalentId(account);
        try {
            iApiService.publishApi(apiParamsRequest);
            result.setCode(200);
        }catch (Exception e){
            result.setCode(500);
            result.setMessage("发布失败"+e.getMessage());
            e.printStackTrace();
        }

        return result;
    }


    //获取api分类列表
    @GetMapping("/system/api/findAllCatelogies")
    public Result findAllCatelogies(){
        Result result = new Result();
        result.setData(iApiService.findAllCatelogies());
        return result;
    }
    @PostMapping("/system/api/approve/{apiid}")
    public Result approveApi(@PathVariable("apiid") String apiId){
        Result result = new Result();
        System.out.println(apiId);
        try {
            iApiService.approveApi(apiId);
        }catch (Exception e){
            result.setCode(500);
            result.setMessage(e.getMessage());
        }

        return result;
    }

    @PostMapping("/system/api/reject/{apiid}")
    public Result rejectApi(
            @PathVariable("apiid") String apiId,
            @RequestBody ApiReject apiReject, @RequestHeader(value = "Authorization", required = false)
                    String authorizationHeader) {
        String account =
                new JwtTokenUtil().
                        getAccountFromToken(extractTokenFromHeader(authorizationHeader));
        Result result = new Result();
        apiReject.setAccount(account);
        apiReject.setTime(new Date());
        apiReject.setApiid(apiId);
        try {
            iApiService.rejectApi(apiReject);
            result.setCode(200);
            result.setMessage("成功拒绝");
        } catch (SQLException e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(500);
        }


        return result;
    }
    @GetMapping("/system/api/apiReject/{apiid}")
    public Result getRejectReason(@PathVariable String apiid ){
        Result result = new Result();
        ApiReject reject = iApiService.findReject(apiid);
        result.setData(reject);
        return result;
    }

    @GetMapping("/histroy/log/api/{apiid}")
    public Result apiLogList(@PathVariable("apiid") String apiid){
        Result result = new Result();
        result.setData(iApiService.findApiRequestLog(apiid));
        return result;
    }
    @GetMapping("/histroy/count/api/{apiid}")
    public Result getApiCount(@PathVariable("apiid") String apiid){
        Result result = new Result();
        result.setData(iApiService.getApiCount(apiid));
        return result;
    }

    @PostMapping("/system/api/params/save")
    public Result saveParms(@RequestBody ApiParameterRequest apiParameterRequest){
        List<ApiParams> apiParams = new ArrayList<>();
        for(ApiParameterDTO apiParameterDTO: apiParameterRequest.getParameters()){
            ApiParams apiParams1 = new ApiParams();
            apiParams1.setApiId(apiParameterRequest.getApiId());
            apiParams1.setParamName(apiParameterDTO.getParamName());
            apiParams1.setParamType(apiParameterDTO.getParamType());
            apiParams1.setNeed(apiParameterDTO.getIsRequired()?1:0);
            apiParams1.setType(Integer.parseInt(apiParameterDTO.getParamDirection()));
            apiParams1.setNote(apiParameterDTO.getRemark());
            apiParams1.setEg(apiParameterDTO.getExample());
            apiParams.add(apiParams1);
        }
        iApiService.addApiParams(apiParams);

        return null;
    }




    @PostMapping("/system/api/author/configPublish")
    public Result configurePublish(@RequestBody ApiPublishConfigRequest request,
                                   @RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
        Result result = new Result();
        try {
            String account = new JwtTokenUtil().getAccountFromToken(extractTokenFromHeader(authorizationHeader));

            // 验证API所有权
            if (!iApiService.validateApiOwnership(request.getApiId(), account)) {
                result.setCode(403);
                result.setMessage("无权操作此API");
                return result;
            }

            // 保存发布配置
            iApiService.savePublishConfig(request);

            result.setCode(200);
            result.setMessage("发布配置保存成功");
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("保存失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/system/api/author/getPublishConfig/{apiId}")
    public Result getPublishConfig(@PathVariable("apiId") Long apiId,
                                   @RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
        Result result = new Result();
        try {
            String account = new JwtTokenUtil().getAccountFromToken(extractTokenFromHeader(authorizationHeader));

            // 验证API所有权
            if (!iApiService.validateApiOwnership(apiId, account)) {
                result.setCode(403);
                result.setMessage("无权查看此API配置");
                return result;
            }

            // 获取发布配置
            ApiPublishConfig config = iApiService.getPublishConfig(apiId);
            result.setData(config);
            result.setCode(200);
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("获取配置失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @PutMapping("/system/api/author/offline/{apiId}")
    public Result offlineApi(@PathVariable("apiId") Long apiId,
                             @RequestHeader(value = "Authorization", required = false) String authorizationHeader) {
        Result result = new Result();
        try {
            String account = new JwtTokenUtil().getAccountFromToken(extractTokenFromHeader(authorizationHeader));

            // 验证API所有权
            if (!iApiService.validateApiOwnership(apiId, account)) {
                result.setCode(403);
                result.setMessage("无权操作此API");
                return result;
            }

            // 下架API
            iApiService.offlineApi(apiId);

            result.setCode(200);
            result.setMessage("API下架成功");
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage("下架失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping("/system/api/author/publish/{apiid}")
    public Result publishApi(@PathVariable("apiid") String apiid){
        iApiService.publishApi(apiid);
        Result result = new Result();
        result.setMessage("成功");
        result.setCode(200);
        return result;
    }

    @PostMapping("/system/api/author/reSubmit/{apiid}")
    public Result reAudit(@PathVariable("apiid") String apiid){
        iApiService.reAudit(Long.parseLong(apiid));
        Result result = new Result();
        result.setMessage("成功");
        result.setCode(200);
        return result;
    }
    @GetMapping("/getBaseUrl/bocker")
    public Result getBaseUrl(){
        return Result.success(baseUrl);
    }




}
